package code

import com.google.protobuf.MessageLite

import common.Message
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelPromise
import io.netty.handler.codec.MessageToByteEncoder
import utils.ByteUtils

/**
 * 客户端编码
 * 将mymessage转成二进制
 * @author King
 */
class PBMssageToBytesEncode : MessageToByteEncoder<Message>() {

    @Throws(Exception::class)
    override fun close(ctx: ChannelHandlerContext, promise: ChannelPromise) {
        super.close(ctx, promise)
    }


    @Throws(Exception::class)
    override fun encode(ctx: ChannelHandlerContext, msg: Message?, out: ByteBuf) {
        var msg = msg
        ByteUtils.writeVariaInt(msg!!.getmId(), out)
        ByteUtils.writeVariaInt(msg.gethId(), out)
        ByteUtils.writeVariaInt(msg.responseId, out)
        var bytes: ByteArray? = null
        if (msg.getBody<Any>() != null) {
            val body = msg.getBody<MessageLite>()
            bytes = body.toByteArray()
        }
        if (bytes != null) {
            out.writeBytes(bytes)
            bytes = null
        }
        msg = null

    }
}
